import React, { useState, useEffect } from 'react'
import { Plus, Edit2, Save, X, Trash2, Upload, Download, FileText } from 'lucide-react'
import { experimentStatisticsAPI, personnelAPI } from '../services/api'

const ExperimentStatistics = () => {
  // 试验分类选择状态
  const [selectedCategory, setSelectedCategory] = useState('振动试验')
  
  // 试验分类配置
  const experimentCategories = [
    { key: '振动试验', label: '振动试验', color: '#e74c3c' },
    { key: '真空热试验', label: '真空热试验', color: '#f39c12' },
    { key: 'EMC试验', label: 'EMC试验', color: '#9b59b6' },
    { key: '磁试验', label: '磁试验', color: '#27ae60' },
    { key: '常压试验', label: '常压试验', color: '#e67e22' }
  ]
  
  // 试验数据 - 从API加载
  const [experiments, setExperiments] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  
  // 人员数据 - 从Personnel API加载
  const [personnelList, setPersonnelList] = useState([])
  const [personnelLoading, setPersonnelLoading] = useState(true)
  
  // 附件弹窗状态
  const [attachmentModalOpen, setAttachmentModalOpen] = useState(false)
  const [currentExperiment, setCurrentExperiment] = useState(null)

  // 编辑状态
  const [editingCell, setEditingCell] = useState(null)
  const [editValue, setEditValue] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingExperiment, setEditingExperiment] = useState(null)
  const [formData, setFormData] = useState({
    experimentNumber: '',
    experimentName: '',
    testItems: '',
    testEquipment: '',
    experimentCommander: '',
    participants: '',
    isExternalCollaboration: '否',
    testCompany: '',
    testContact: '',
    participantName: '',
    productQuantity: '',
    productNumber: '',
    productEntryDate: '',
    testStartDate: '',
    testEndDate: '',
    productExitDate: '',
    operatingDays: '',
    reservationApprovalNumber: '',
    photoUploaded: '否',
    summaryReport: '',
    certificateNumber: '',
    contractNumber: '',
    partnerContact: '',
    ourContact: '',
    attachments: []
  })

  // 根据分类过滤试验数据
  const filteredExperiments = experiments.filter(exp => exp.experimentType === selectedCategory)

  // 注意：试验编号现在由后端自动生成，前端不再需要生成逻辑

  // 从API加载试验数据
  useEffect(() => {
    const loadExperiments = async () => {
      try {
        setLoading(true)
        setError(null)
        const data = await experimentStatisticsAPI.getAll()
        setExperiments(data.results || [])
      } catch (err) {
        console.error('加载试验数据失败:', err)
        setError('加载试验数据失败，请检查网络连接')
        // 如果API失败，尝试从localStorage加载备份数据
        const saved = localStorage.getItem('experimentSystem_experiments')
        if (saved) {
          setExperiments(JSON.parse(saved))
        }
      } finally {
        setLoading(false)
      }
    }

    loadExperiments()
  }, [])

  // 从API加载人员数据
  useEffect(() => {
    const loadPersonnel = async () => {
      try {
        setPersonnelLoading(true)
        const data = await personnelAPI.getAll()
        setPersonnelList(data.results || [])
      } catch (err) {
        console.error('加载人员数据失败:', err)
        // 如果API失败，设置空数组
        setPersonnelList([])
      } finally {
        setPersonnelLoading(false)
      }
    }

    loadPersonnel()
  }, [])

  // 备份数据到localStorage（作为离线缓存）
  useEffect(() => {
    if (experiments.length > 0) {
      localStorage.setItem('experimentSystem_experiments', JSON.stringify(experiments))
    }
  }, [experiments])

  // 自动计算开机天数（仅适用于真空热试验）
  useEffect(() => {
    if (selectedCategory === '真空热试验' && formData.testStartDate && formData.testEndDate) {
      const startDate = new Date(formData.testStartDate)
      const endDate = new Date(formData.testEndDate)
      
      if (startDate <= endDate) {
        // 计算两个日期之间的天数差（包含开始和结束日期）
        const timeDiff = endDate.getTime() - startDate.getTime()
        const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1
        
        // 只有当计算出的天数与当前开机天数不同时才更新
        if (formData.operatingDays !== daysDiff.toString()) {
          setFormData(prev => ({
            ...prev,
            operatingDays: daysDiff.toString()
          }))
        }
      }
    }
  }, [formData.testStartDate, formData.testEndDate, selectedCategory])

  // 计算开机天数的辅助函数
  const calculateOperatingDays = (startDate, endDate) => {
    if (!startDate || !endDate) return ''
    
    const start = new Date(startDate)
    const end = new Date(endDate)
    
    if (start <= end) {
      const timeDiff = end.getTime() - start.getTime()
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1
      return daysDiff.toString()
    }
    
    return ''
  }

  // 鼠标拖拽滚动功能
  useEffect(() => {
    const tableContainer = document.querySelector('.table-container')
    if (!tableContainer) return

    let isDown = false
    let startX
    let scrollLeft

    const handleMouseDown = (e) => {
      isDown = true
      tableContainer.style.cursor = 'grabbing'
      startX = e.pageX - tableContainer.offsetLeft
      scrollLeft = tableContainer.scrollLeft
    }

    const handleMouseLeave = () => {
      isDown = false
      tableContainer.style.cursor = 'grab'
    }

    const handleMouseUp = () => {
      isDown = false
      tableContainer.style.cursor = 'grab'
    }

    const handleMouseMove = (e) => {
      if (!isDown) return
      e.preventDefault()
      const x = e.pageX - tableContainer.offsetLeft
      const walk = (x - startX) * 2 // 滚动速度
      tableContainer.scrollLeft = scrollLeft - walk
    }

    tableContainer.addEventListener('mousedown', handleMouseDown)
    tableContainer.addEventListener('mouseleave', handleMouseLeave)
    tableContainer.addEventListener('mouseup', handleMouseUp)
    tableContainer.addEventListener('mousemove', handleMouseMove)

    return () => {
      tableContainer.removeEventListener('mousedown', handleMouseDown)
      tableContainer.removeEventListener('mouseleave', handleMouseLeave)
      tableContainer.removeEventListener('mouseup', handleMouseUp)
      tableContainer.removeEventListener('mousemove', handleMouseMove)
    }
  }, [experiments])

  // 点击外部区域关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event) => {
      // 关闭表单中的下拉框
      const commanderDropdown = document.getElementById('commander-dropdown')
      const participantsDropdown = document.getElementById('participants-dropdown')
      
      if (commanderDropdown && !event.target.closest('#commander-dropdown') && !event.target.closest('[data-dropdown="commander"]')) {
        commanderDropdown.style.display = 'none'
      }
      
      if (participantsDropdown && !event.target.closest('#participants-dropdown') && !event.target.closest('[data-dropdown="participants"]')) {
        participantsDropdown.style.display = 'none'
      }
      
      // 关闭表格中的多选下拉框
      const tableDropdowns = document.querySelectorAll('[id^="table-"][id$="-dropdown"]')
      tableDropdowns.forEach(dropdown => {
        if (dropdown.style.display === 'block' && !event.target.closest(`#${dropdown.id}`) && !dropdown.previousElementSibling.contains(event.target)) {
          dropdown.style.display = 'none'
        }
      })
    }

    document.addEventListener('click', handleClickOutside)
    return () => {
      document.removeEventListener('click', handleClickOutside)
    }
  }, [showAddForm])

  // 开始编辑
  const startEdit = (id, field) => {
    const experiment = experiments.find(e => e.id === id)
    const value = experiment ? experiment[field] : ''
    console.log('startEdit:', field, 'value:', value, 'experiment:', experiment)
    setEditingCell(`${id}-${field}`)
    setEditValue(value || '')
  }

  // 保存编辑
  const saveEdit = async () => {
    if (!editingCell) return
    
    const [id, field] = editingCell.split('-')
    const experimentId = parseInt(id)
    
    try {
      // 调用API更新数据
      await experimentStatisticsAPI.patch(experimentId, { [field]: editValue })
      
      // 更新本地状态
      setExperiments(prev => prev.map(experiment => {
        if (experiment.id === experimentId) {
          const updatedExperiment = { ...experiment, [field]: editValue }
          
          // 如果是真空热试验且修改的是试验开始日期或结束日期，自动计算开机天数
          if (experiment.experimentType === '真空热试验' && 
              (field === 'testStartDate' || field === 'testEndDate')) {
            const startDate = field === 'testStartDate' ? editValue : experiment.testStartDate
            const endDate = field === 'testEndDate' ? editValue : experiment.testEndDate
            
            if (startDate && endDate) {
              const start = new Date(startDate)
              const end = new Date(endDate)
              
              if (start <= end) {
                // 计算两个日期之间的天数差（包含开始和结束日期）
                const timeDiff = end.getTime() - start.getTime()
                const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1
                updatedExperiment.operatingDays = daysDiff.toString()
                
                // 同时更新数据库中的开机天数
                experimentStatisticsAPI.patch(experimentId, { operatingDays: daysDiff.toString() })
                  .catch(err => console.error('更新开机天数失败:', err))
              }
            }
          }
          
          return updatedExperiment
        }
        return experiment
      }))
      
      setEditingCell(null)
      setEditValue('')
    } catch (err) {
      console.error('保存编辑失败:', err)
      setError('保存失败，请重试')
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingCell(null)
    setEditValue('')
  }

  // 开始修改试验
  const startEditExperiment = (experiment) => {
    setEditingExperiment(experiment.id)
    setFormData({
      experimentNumber: experiment.experimentNumber || '',
      experimentName: experiment.experimentName || '',
      productType: experiment.productType || '',
      testItems: experiment.testItems || '',
      testEquipment: experiment.testEquipment || '',
      experimentCommander: experiment.experimentCommander || '',
      participants: experiment.participants || '',
      isExternalCollaboration: experiment.isExternalCollaboration || '否',
      testCompany: experiment.testCompany || '',
      testContact: experiment.testContact || '',
      participantName: experiment.participantName || '',
      productQuantity: experiment.productQuantity || '',
      productNumber: experiment.productNumber || '',
      productEntryDate: experiment.productEntryDate || '',
      testStartDate: experiment.testStartDate || '',
      testEndDate: experiment.testEndDate || '',
      productExitDate: experiment.productExitDate || '',
      operatingDays: experiment.operatingDays || '',
      reservationApprovalNumber: experiment.reservationApprovalNumber || '',
      photoUploaded: experiment.photoUploaded || '否',
      summaryReport: experiment.summaryReport || '',
      certificateNumber: experiment.certificateNumber || '',
      contractNumber: experiment.contractNumber || '',
      partnerContact: experiment.partnerContact || '',
      ourContact: experiment.ourContact || '',
      attachments: experiment.attachments || []
    })
    setShowAddForm(true)
  }

  // 添加或修改试验
  const handleSubmit = (e) => {
    e.preventDefault()
    if (editingExperiment) {
      updateExperiment()
    } else {
      addExperiment()
    }
  }

  // 添加新试验
   const addExperiment = async () => {
     
     let newExperiment
     try {
       // 准备API数据
       const apiData = {
         ...formData,
         // 根据当前选中的试验类型自动设置experiment_type字段
         experimentType: selectedCategory,
         // 只有真空热试验才保存开机天数，其他试验类型将开机天数设为空
         operatingDays: selectedCategory === '真空热试验' ? formData.operatingDays : ''
       }
       
       // 调用API创建新试验
       newExperiment = await experimentStatisticsAPI.create(apiData)
       
       // 如果有附件，上传附件
       if (formData.attachments && formData.attachments.length > 0) {
         try {
           for (const attachment of formData.attachments) {
             // 使用FormData发送实际文件
             const fileFormData = new FormData()
             fileFormData.append('file', attachment.file)
             await experimentStatisticsAPI.addAttachment(newExperiment.id, fileFormData)
           }
         } catch (attachmentErr) {
           console.error('上传附件失败:', attachmentErr)
           setError('试验创建成功，但附件上传失败，请稍后重试')
         }
       }
       
       // 重新从服务器加载所有数据以确保数据同步
       const data = await experimentStatisticsAPI.getAll()
       setExperiments(data.results || [])
     } catch (err) {
       console.error('添加试验失败:', err)
       setError('添加试验失败，请重试')
       return
     }
     
     // 重置表单
     setFormData({
       experimentNumber: '',
       experimentName: '',
       productType: '',
       testItems: '',
       testEquipment: '',
       experimentCommander: '',
       participants: '',
       isExternalCollaboration: '否',
       testCompany: '',
       testContact: '',
       participantName: '',
       productQuantity: '',
       productNumber: '',
       productEntryDate: '',
       testStartDate: '',
       testEndDate: '',
       productExitDate: '',
       operatingDays: '',
       reservationApprovalNumber: '',
       photoUploaded: '否',
       summaryReport: '',
       certificateNumber: '',
       contractNumber: '',
       partnerContact: '',
       ourContact: '',
       attachments: []
     })
     setEditingExperiment(null)
     setShowAddForm(false)
   }

  // 更新试验信息
  const updateExperiment = async () => {

    try {
      // 准备API数据
      const apiData = {
        ...formData,
        // 根据当前选中的试验类型自动设置experiment_type字段
        experimentType: selectedCategory,
        operatingDays: selectedCategory === '真空热试验' ? formData.operatingDays : ''
      }
      
      // 调用API更新试验
      const updatedExperiment = await experimentStatisticsAPI.update(editingExperiment, apiData)
      
      // 如果有新的附件，上传附件
      if (formData.attachments && formData.attachments.length > 0) {
        try {
          // 获取现有试验的附件，避免重复上传
          const existingExperiment = experiments.find(exp => exp.id === editingExperiment)
          const existingAttachmentIds = existingExperiment?.attachments?.map(att => att.id) || []
          
          // 只上传新的附件（没有在现有附件中的）
          const newAttachments = formData.attachments.filter(att => !existingAttachmentIds.includes(att.id))
          
          for (const attachment of newAttachments) {
            // 使用FormData发送实际文件
            const fileFormData = new FormData()
            fileFormData.append('file', attachment.file)
            await experimentStatisticsAPI.addAttachment(editingExperiment, fileFormData)
          }
        } catch (attachmentErr) {
          console.error('上传附件失败:', attachmentErr)
          setError('试验更新成功，但附件上传失败，请稍后重试')
        }
      }
      
      // 重新从服务器加载所有数据以确保数据同步
      const data = await experimentStatisticsAPI.getAll()
      setExperiments(data.results || [])
    } catch (err) {
      console.error('更新试验失败:', err)
      setError('更新试验失败，请重试')
      return
    }
    
    // 关闭表单并重置状态
    setShowAddForm(false)
    setEditingExperiment(null)
    setFormData({
      experimentNumber: '',
      experimentName: '',
      testItems: '',
      testEquipment: '',
      experimentCommander: '',
      participants: '',
      isExternalCollaboration: '否',
      testCompany: '',
      testContact: '',
      participantName: '',
      productQuantity: '',
      productNumber: '',
      productEntryDate: '',
      testStartDate: '',
      testEndDate: '',
      productExitDate: '',
      operatingDays: '',
      reservationApprovalNumber: '',
      photoUploaded: '否',
      summaryReport: '',
      certificateNumber: '',
      contractNumber: '',
      partnerContact: '',
      ourContact: '',
      attachments: []
    });
  }

  // 删除试验
  const deleteExperiment = async (id) => {
    if (window.confirm('确定要删除这个试验吗？')) {
      try {
        // 调用API删除试验
        await experimentStatisticsAPI.delete(id)
        
        // 更新本地状态
        setExperiments(prev => prev.filter(experiment => experiment.id !== id))
      } catch (err) {
        console.error('删除试验失败:', err)
        setError('删除试验失败，请重试')
      }
    }
  }

  // 文件上传处理
  const handleFileUpload = async (e, isFormUpload = false) => {
    console.log('handleFileUpload called:', { isFormUpload, editingCell })
    const files = Array.from(e.target.files)
    console.log('Selected files:', files.map(f => ({ name: f.name, size: f.size })))
    
    if (files.length === 0) {
      console.log('No files selected')
      return
    }

    if (isFormUpload) {
      // 表单中的文件上传 - 只添加到表单状态，保存时统一上传
      const newAttachments = files.map(file => ({
        id: Date.now() + Math.random(),
        name: file.name,
        size: file.size,
        type: file.type,
        uploadTime: new Date().toLocaleString(),
        file: file  // 保存实际的文件对象
      }))
      
      setFormData(prev => ({
        ...prev,
        attachments: [...prev.attachments, ...newAttachments]
      }))
    } else {
      // 内联编辑中的文件上传 - 立即上传到数据库
      console.log('Processing inline upload, editingCell:', editingCell)
      if (editingCell) {
        const [id, field] = editingCell.split('-')
        console.log('Parsed editingCell:', { id, field })
        if (field === 'testItems') {
          const experimentId = parseInt(id)
          console.log('Uploading to experiment ID:', experimentId)
          
          try {
            // 逐个上传文件到数据库
            const uploadedAttachments = []
            for (const file of files) {
              console.log('Uploading file:', file.name)
              const fileFormData = new FormData()
              fileFormData.append('file', file)
              
              const uploadedAttachment = await experimentStatisticsAPI.addAttachment(experimentId, fileFormData)
              console.log('Upload successful:', uploadedAttachment)
              uploadedAttachments.push(uploadedAttachment)
            }
            
            // 更新前端状态，添加已上传的附件
            setExperiments(prev => prev.map(experiment => 
              experiment.id === experimentId
                ? { 
                    ...experiment, 
                    attachments: [...(experiment.attachments || []), ...uploadedAttachments]
                  }
                : experiment
            ))
            console.log('Frontend state updated successfully')
          } catch (err) {
            console.error('上传附件失败:', err)
            setError('上传附件失败，请重试')
          }
        } else {
          console.log('Field is not testItems:', field)
        }
      } else {
        console.log('No editingCell set')
      }
    }
  }

  // 删除附件
  const removeAttachment = async (attachmentId, isFormRemoval = false, experimentId = null) => {
    if (isFormRemoval) {
      // 表单中删除附件（新上传但未保存的附件）
      setFormData(prev => ({
        ...prev,
        attachments: prev.attachments.filter(att => att.id !== attachmentId)
      }))
    } else if (experimentId) {
      // 试验记录中删除附件（已保存到数据库的附件）
      try {
        // 调用后端API删除数据库记录
        await experimentStatisticsAPI.deleteAttachment(attachmentId)
        
        // 更新前端状态
        setExperiments(prev => prev.map(experiment => 
          experiment.id === experimentId 
            ? { 
                ...experiment, 
                attachments: (experiment.attachments || []).filter(att => att.id !== attachmentId)
              }
            : experiment
        ))
      } catch (err) {
        console.error('删除附件失败:', err)
        setError('删除附件失败，请重试')
      }
    }
  }

  // 下载附件
  const downloadAttachment = async (attachmentId, fileName) => {
    try {
      const blob = await experimentStatisticsAPI.downloadAttachment(attachmentId)
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (err) {
      console.error('下载附件失败:', err)
      setError('下载附件失败，请重试')
    }
  }

  // 预览附件
  const previewAttachment = (attachmentId) => {
    const previewUrl = experimentStatisticsAPI.previewAttachment(attachmentId)
    window.open(previewUrl, '_blank')
  }

  // 渲染总结报告/证明书列（下拉选择或手填）
  const renderSummaryReportCell = (experiment) => {
    const cellKey = `${experiment.id}-summaryReport`
    const isEditing = editingCell === cellKey
    
    if (isEditing) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
          <select
            value={editValue === '信息化归档' || editValue === '未编制' ? editValue : ''}
            onChange={(e) => setEditValue(e.target.value)}
            style={{ 
              flex: 1, 
              padding: '4px', 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              fontSize: '12px'
            }}
          >
            <option value="">请选择或手填</option>
            <option value="信息化归档">信息化归档</option>
            <option value="未编制">未编制</option>
          </select>
          <input
            type="text"
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            placeholder="或手动输入"
            style={{ 
              flex: 1, 
              padding: '4px', 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              fontSize: '12px'
            }}
          />
          <button 
            onClick={saveEdit} 
            title="保存"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#27ae60', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px'
            }}
          >
            ✓
          </button>
          <button 
            onClick={cancelEdit} 
            title="取消"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#e74c3c', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px'
            }}
          >
            ✕
          </button>
        </div>
      )
    }
    
    return (
      <div 
        onClick={() => startEdit(experiment.id, 'summaryReport')}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          fontSize: '12px',
          color: experiment.summaryReport ? '#333' : '#999'
        }}
        title="点击编辑总结报告/证明书"
      >
        {experiment.summaryReport || '点击编辑'}
      </div>
    )
  }

  // 打开附件管理弹窗
  const openAttachmentModal = (experiment) => {
    setCurrentExperiment(experiment)
    setAttachmentModalOpen(true)
  }

  // 关闭附件管理弹窗
  const closeAttachmentModal = () => {
    setAttachmentModalOpen(false)
    setCurrentExperiment(null)
  }

  // 附件弹窗中的文件上传处理
  const handleModalFileUpload = async (files) => {
    if (!currentExperiment || !files.length) return

    try {
      const uploadedAttachments = []
      
      for (const file of files) {
        const fileFormData = new FormData()
        fileFormData.append('file', file)
        
        const uploadedAttachment = await experimentStatisticsAPI.addAttachment(currentExperiment.id, fileFormData)
        uploadedAttachments.push(uploadedAttachment)
      }
      
      // 更新前端状态
      setExperiments(prev => prev.map(experiment => 
        experiment.id === currentExperiment.id
          ? { 
              ...experiment, 
              attachments: [...(experiment.attachments || []), ...uploadedAttachments]
            }
          : experiment
      ))
      
      // 更新当前实验数据
      setCurrentExperiment(prev => ({
        ...prev,
        attachments: [...(prev.attachments || []), ...uploadedAttachments]
      }))
      
    } catch (err) {
      console.error('上传附件失败:', err)
      setError('上传附件失败，请重试')
    }
  }

  // 附件弹窗中的删除处理
  const handleModalRemoveAttachment = async (attachmentId) => {
    if (!currentExperiment) return

    try {
      await experimentStatisticsAPI.deleteAttachment(attachmentId)
      
      // 更新前端状态
      setExperiments(prev => prev.map(experiment => 
        experiment.id === currentExperiment.id
          ? { 
              ...experiment, 
              attachments: experiment.attachments.filter(att => att.id !== attachmentId)
            }
          : experiment
      ))
      
      // 更新当前实验数据
      setCurrentExperiment(prev => ({
        ...prev,
        attachments: prev.attachments.filter(att => att.id !== attachmentId)
      }))
      
    } catch (err) {
      console.error('删除附件失败:', err)
      setError('删除附件失败，请重试')
    }
  }

  // 渲染附件管理弹窗
  const renderAttachmentModal = () => {
    if (!attachmentModalOpen || !currentExperiment) return null

    const attachments = currentExperiment.attachments || []

    return (
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000
      }}>
        <div style={{
          backgroundColor: 'white',
          borderRadius: '8px',
          padding: '24px',
          width: '600px',
          maxHeight: '80vh',
          overflow: 'auto'
        }}>
          {/* 弹窗标题 */}
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '20px',
            borderBottom: '1px solid #eee',
            paddingBottom: '12px'
          }}>
            <h3 style={{ margin: 0, fontSize: '18px', fontWeight: '600' }}>
              附件管理 - {currentExperiment.experimentName || currentExperiment.experimentNumber}
            </h3>
            <button
              onClick={closeAttachmentModal}
              style={{
                background: 'none',
                border: 'none',
                fontSize: '20px',
                cursor: 'pointer',
                color: '#999'
              }}
            >
              ×
            </button>
          </div>

          {/* 上传区域 */}
          <div style={{
            border: '2px dashed #ddd',
            borderRadius: '8px',
            padding: '20px',
            textAlign: 'center',
            marginBottom: '20px',
            backgroundColor: '#fafafa'
          }}>
            <input
              type="file"
              multiple
              onChange={(e) => {
                if (e.target.files.length > 0) {
                  handleModalFileUpload(Array.from(e.target.files))
                  e.target.value = '' // 清空input以便重复选择同一文件
                }
              }}
              style={{ display: 'none' }}
              id="modal-file-upload"
            />
            <div style={{ marginBottom: '12px' }}>
              <Upload size={32} style={{ color: '#3498db' }} />
            </div>
            <button
              onClick={() => document.getElementById('modal-file-upload').click()}
              style={{
                padding: '10px 20px',
                fontSize: '14px',
                background: '#3498db',
                color: 'white',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                margin: '0 auto'
              }}
            >
              <Upload size={16} />
              选择文件上传
            </button>
            <p style={{ margin: '8px 0 0 0', fontSize: '12px', color: '#666' }}>
              支持多文件选择，点击按钮或拖拽文件到此区域
            </p>
          </div>

          {/* 附件列表 */}
          <div style={{ marginBottom: '20px' }}>
            <h4 style={{ margin: '0 0 12px 0', fontSize: '16px' }}>
              已上传附件 ({attachments.length})
            </h4>
            
            {attachments.length === 0 ? (
              <div style={{
                textAlign: 'center',
                padding: '40px',
                color: '#999',
                fontSize: '14px'
              }}>
                暂无附件
              </div>
            ) : (
              <div style={{
                maxHeight: '300px',
                overflowY: 'auto',
                border: '1px solid #eee',
                borderRadius: '6px'
              }}>
                {attachments.map(attachment => (
                  <div key={attachment.id} style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    padding: '12px 16px',
                    borderBottom: '1px solid #f5f5f5',
                    ':last-child': { borderBottom: 'none' }
                  }}>
                    <div style={{
                      display: 'flex',
                      alignItems: 'center',
                      flex: 1,
                      minWidth: 0
                    }}>
                      <FileText size={20} style={{ marginRight: '12px', color: '#666', flexShrink: 0 }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{
                          fontSize: '14px',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }} title={attachment.name}>
                          {attachment.name}
                        </div>
                        <div style={{
                          fontSize: '12px',
                          color: '#999',
                          marginTop: '2px'
                        }}>
                          {attachment.size ? `${(attachment.size / 1024).toFixed(1)} KB` : ''} • 
                          {attachment.upload_time ? new Date(attachment.upload_time).toLocaleString() : ''}
                        </div>
                      </div>
                    </div>
                    
                    <div style={{ display: 'flex', gap: '8px', marginLeft: '12px' }}>
                      <button
                        onClick={() => previewAttachment(attachment.id)}
                        style={{
                          padding: '6px 12px',
                          fontSize: '12px',
                          background: '#28a745',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        title="预览"
                      >
                        <FileText size={12} />
                        预览
                      </button>
                      <button
                        onClick={() => downloadAttachment(attachment.id, attachment.name)}
                        style={{
                          padding: '6px 12px',
                          fontSize: '12px',
                          background: '#3498db',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        title="下载"
                      >
                        <Download size={12} />
                        下载
                      </button>
                      <button
                        onClick={() => {
                          if (window.confirm('确定要删除这个附件吗？')) {
                            handleModalRemoveAttachment(attachment.id)
                          }
                        }}
                        style={{
                          padding: '6px 12px',
                          fontSize: '12px',
                          background: '#e74c3c',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        title="删除"
                      >
                        <Trash2 size={12} />
                        删除
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 关闭按钮 */}
          <div style={{ textAlign: 'right' }}>
            <button
              onClick={closeAttachmentModal}
              style={{
                padding: '8px 16px',
                fontSize: '14px',
                background: '#6c757d',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer'
              }}
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    )
  }

  // 渲染原始记录上传列（简化版，只显示编辑按钮）
  const renderAttachmentCell = (experiment) => {
    const attachments = experiment.attachments || []
    
    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        minWidth: '100px'
      }}>
        <button 
          onClick={() => openAttachmentModal(experiment)}
          title="管理附件"
          style={{ 
            padding: '6px 12px', 
            fontSize: '12px', 
            background: '#3498db', 
            color: 'white', 
            border: 'none', 
            borderRadius: '4px',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          }}
        >
          <Edit2 size={12} />
          管理附件 ({attachments.length})
        </button>
      </div>
    )
  }

  // 渲染编辑单元格
  const renderEditableCell = (id, field, value, isSelect = false, selectOptions = []) => {
    const cellKey = `${id}-${field}`
    const isEditing = editingCell === cellKey
    const isPersonnelField = field === 'experimentCommander' || field === 'participants'
    
    if (isEditing) {
      if (isSelect && isPersonnelField) {
        // 人员字段使用多选界面
        return (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: '4px', minWidth: '200px' }}>
            <div style={{ flex: 1, position: 'relative' }}>
              <div 
                style={{ 
                  minHeight: '28px',
                  padding: '4px', 
                  border: '1px solid #d9d9d9', 
                  borderRadius: '4px',
                  backgroundColor: 'white',
                  cursor: 'pointer',
                  display: 'flex',
                  flexWrap: 'wrap',
                  gap: '2px',
                  alignItems: 'center',
                  fontSize: '12px'
                }}
                onClick={(e) => {
                  const dropdown = document.getElementById(`table-${cellKey}-dropdown`)
                  if (dropdown) {
                    if (dropdown.style.display === 'block') {
                      dropdown.style.display = 'none'
                    } else {
                      const rect = e.currentTarget.getBoundingClientRect()
                      dropdown.style.display = 'block'
                      dropdown.style.top = `${rect.bottom + window.scrollY}px`
                      dropdown.style.left = `${rect.left + window.scrollX}px`
                    }
                  }
                }}
              >
                {editValue ? 
                  editValue.split(',').map((name, index) => (
                    <span key={index} style={{
                      backgroundColor: '#e6f7ff',
                      border: '1px solid #91d5ff',
                      borderRadius: '3px',
                      padding: '1px 4px',
                      fontSize: '11px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '2px'
                    }}>
                      {name.trim()}
                      <span 
                        style={{ cursor: 'pointer', fontWeight: 'bold' }}
                        onClick={(e) => {
                          e.stopPropagation()
                          const names = editValue.split(',').filter(n => n.trim() !== name.trim())
                          setEditValue(names.join(','))
                        }}
                      >
                        ×
                      </span>
                    </span>
                  )) : 
                  <span style={{ color: '#999', fontSize: '11px' }}>点击选择人员</span>
                }
              </div>
              <div 
                id={`table-${cellKey}-dropdown`}
                style={{
                  position: 'fixed',
                  top: '100%',
                  left: 0,
                  minWidth: '200px',
                  backgroundColor: 'white',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  maxHeight: '150px',
                  overflowY: 'auto',
                  zIndex: 9999,
                  display: 'none',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
                }}
              >
                {selectOptions.map(option => {
                  const isSelected = editValue ? editValue.split(',').map(n => n.trim()).includes(option.value) : false
                  return (
                    <div
                      key={option.value}
                      style={{
                        padding: '6px 8px',
                        cursor: 'pointer',
                        backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                        fontSize: '12px',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '4px'
                      }}
                      onClick={(e) => {
                        e.stopPropagation()
                        let newValue
                        if (isSelected) {
                          const names = editValue ? editValue.split(',').filter(n => n.trim() !== option.value) : []
                          newValue = names.join(',')
                        } else {
                          const names = editValue ? editValue.split(',') : []
                          names.push(option.value)
                          newValue = names.join(',')
                        }
                        setEditValue(newValue)
                      }}
                    >
                      <input 
                        type="checkbox" 
                        checked={isSelected} 
                        readOnly 
                        style={{ marginRight: '4px' }}
                      />
                      {option.label}
                    </div>
                  )
                })}
              </div>
            </div>
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✕
            </button>
          </div>
        )
      } else if (isSelect) {
        // 其他选择字段使用单选下拉框
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <select
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              style={{ 
                flex: 1, 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '12px'
              }}
            >
              {!editValue && <option value="">请选择...</option>}
              {selectOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✕
            </button>
          </div>
        )
      } else {
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <input
              type="text"
              value={editValue}
              onChange={(e) => setEditValue(e.target.value)}
              style={{ 
                flex: 1, 
                padding: '4px', 
                border: '1px solid #d9d9d9', 
                borderRadius: '4px',
                fontSize: '12px'
              }}
            />
            <button 
              onClick={saveEdit} 
              title="保存"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#27ae60', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✓
            </button>
            <button 
              onClick={cancelEdit} 
              title="取消"
              style={{ 
                padding: '4px', 
                fontSize: '12px', 
                background: '#e74c3c', 
                color: 'white', 
                border: 'none', 
                borderRadius: '3px'
              }}
            >
              ✕
            </button>
          </div>
        )
      }
    }
    
    return (
      <div 
        onClick={() => startEdit(id, field)}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: value ? '#333' : '#999'
        }}
        title="点击编辑"
      >
        {value || '点击编辑'}
      </div>
    )
  }

  // 渲染试验项目单元格（删除上传文档功能）
  const renderTestItemsCell = (experiment) => {
    const cellKey = `${experiment.id}-testItems`
    const isEditing = editingCell === cellKey
    
    if (isEditing) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '4px', minWidth: '200px' }}>
          <input
            type="text"
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            placeholder="试验项目"
            style={{ 
              flex: 1, 
              padding: '4px', 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              fontSize: '12px'
            }}
          />
          <button 
            onClick={saveEdit} 
            title="保存"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#27ae60', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px'
            }}
          >
            ✓
          </button>
          <button 
            onClick={cancelEdit} 
            title="取消"
            style={{ 
              padding: '4px', 
              fontSize: '12px', 
              background: '#e74c3c', 
              color: 'white', 
              border: 'none', 
              borderRadius: '3px'
            }}
          >
            ✕
          </button>
        </div>
      )
    }
    
    return (
      <div 
        onClick={() => startEdit(experiment.id, 'testItems')}
        style={{ 
          cursor: 'pointer', 
          minHeight: '20px', 
          padding: '4px',
          border: '1px solid transparent',
          borderRadius: '4px',
          color: experiment.testItems ? '#333' : '#999'
        }}
        title="点击编辑"
      >
        <div>{experiment.testItems || '点击编辑'}</div>
      </div>
    )
  }

  // 导出Excel功能
  const exportToExcel = () => {
    if (experiments.length === 0) {
      alert('没有数据可导出')
      return
    }

    // 定义表头
    const baseHeaders = [
      '序号', '试验编号', '试验名称', '参试产品类型', '试验项目', '试验设备', '试验指挥',
      '参试人员', '是否为协外试验', '送试方部门/公司', '送试方联系人及电话',
      '参试产品名称', '参试产品数量', '参试产品编号', '产品入场日期',
      '试验开始日期', '试验结束日期', '产品出场日期'
    ]
    
    const endHeaders = [
      '试验预约审批编号', '试验照片是否上传', '总结报告/证明书', '证书归档编号', '合同编号',
      '对方商务联系人及电话', '我方商务联系人及电话', '原始记录上传'
    ]
    
    // 根据当前选择的试验类别决定是否包含开机天数
    const headers = selectedCategory === '真空热试验' 
      ? [...baseHeaders, '开机天数', ...endHeaders]
      : [...baseHeaders, ...endHeaders]

    // 准备数据
    const data = filteredExperiments.map((exp, index) => {
      const baseData = [
        index + 1,
        exp.experimentNumber || '',
        exp.experimentName || '',
        exp.productType || '',
        exp.testItems || '',
        exp.testEquipment || '',
        exp.experimentCommander || '',
        exp.participants || '',
        exp.isExternalCollaboration || '',
        exp.testCompany || '',
        exp.testContact || '',
        exp.participantName || '',
        exp.productQuantity || '',
        exp.productNumber || '',
        exp.productEntryDate || '',
        exp.testStartDate || '',
        exp.testEndDate || '',
        exp.productExitDate || ''
      ]
      
      const endData = [
        exp.reservationApprovalNumber || '',
        exp.photoUploaded || '',
        exp.summaryReport || '',
        exp.certificateNumber || '',
        exp.contractNumber || '',
        exp.partnerContact || '',
        exp.ourContact || '',
        (exp.attachments && exp.attachments.length > 0) ? `${exp.attachments.length}个附件` : '无附件'
      ]
      
      return selectedCategory === '真空热试验' 
        ? [...baseData, calculateOperatingDays(exp.testStartDate, exp.testEndDate) || exp.operatingDays || '', ...endData]
        : [...baseData, ...endData]
    })

    // 创建CSV内容
    const csvContent = [headers, ...data]
      .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n')

    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `试验信息统计_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  return (
    <div className="card">
      <style>
        {`
          .table-container::-webkit-scrollbar {
            height: 12px;
          }
          .table-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 6px;
          }
          .table-container::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 6px;
          }
          .table-container::-webkit-scrollbar-thumb:hover {
            background: #555;
          }
        `}
      </style>
      {/* 试验分类选项卡 */}
      <div style={{ marginBottom: '16px' }}>
        <div style={{ 
          display: 'flex', 
          borderBottom: '2px solid #f0f0f0',
          backgroundColor: '#fafafa',
          borderRadius: '8px 8px 0 0',
          overflow: 'hidden'
        }}>
          {experimentCategories.map(category => (
            <div
              key={category.key}
              onClick={() => setSelectedCategory(category.key)}
              style={{
                padding: '12px 20px',
                cursor: 'pointer',
                fontSize: '14px',
                borderBottom: selectedCategory === category.key ? `3px solid ${category.color}` : '3px solid transparent',
                backgroundColor: selectedCategory === category.key ? 'white' : 'transparent',
                color: selectedCategory === category.key ? category.color : '#666',
                transition: 'all 0.3s ease',
                position: 'relative',
                minWidth: '120px',
                textAlign: 'center'
              }}
            >
              {category.label}
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
      </div>
      
      {/* 加载状态和错误提示 */}
      {loading && (
        <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>
          正在加载试验数据...
        </div>
      )}
      
      {error && (
        <div style={{ 
          background: '#fff2f0', 
          border: '1px solid #ffccc7', 
          borderRadius: '6px', 
          padding: '12px', 
          marginBottom: '16px', 
          color: '#a8071a' 
        }}>
          {error}
          <button 
            onClick={() => setError(null)} 
            style={{ 
              marginLeft: '8px', 
              background: 'none', 
              border: 'none', 
              color: '#a8071a', 
              cursor: 'pointer' 
            }}
          >
            ×
          </button>
        </div>
      )}
      
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
         <div></div>
        <div style={{ display: 'flex', gap: '8px' }}>
          <button 
            className="btn btn-primary"
            onClick={() => {
              setEditingExperiment(null)
              setFormData({
                experimentNumber: '', // 由后端自动生成
                experimentName: '',
                productType: '',
                testItems: '',
                testEquipment: '',
                experimentCommander: '',
                participants: '',
                isExternalCollaboration: '否',
                testCompany: '',
                testContact: '',
                participantName: '',
                productQuantity: '',
                productNumber: '',
                productEntryDate: '',
                testStartDate: '',
                testEndDate: '',
                productExitDate: '',
                operatingDays: '',
                reservationApprovalNumber: '',
                photoUploaded: '否',
                summaryReport: '',
                certificateNumber: '',
                contractNumber: '',
                partnerContact: '',
                ourContact: '',
                attachments: []
              })
              setShowAddForm(true)
            }}
          >
            <Plus size={16} />
            新增试验
          </button>
          <button
            onClick={exportToExcel}
            style={{
              padding: '8px 16px',
              background: '#28a745',
              border: '1px solid #28a745',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              gap: '4px'
            }}
            title="导出试验信息到Excel"
          >
            <Download size={16} />
            导出Excel
          </button>
        </div>
      </div>

      {/* 新增/修改试验表单 */}
      {showAddForm && (
        <div style={{ 
          background: '#f8f9fa', 
          padding: '20px', 
          borderRadius: '8px', 
          marginBottom: '20px',
          border: '1px solid #e9ecef'
        }}>
          <h3 style={{ marginBottom: '16px' }}>
            {editingExperiment ? '修改试验信息' : '新增试验信息'}
          </h3>
          <form onSubmit={handleSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px' }}>
            {/* 试验编号由后端自动生成，前端不显示 */}
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验名称<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.experimentName}
                onChange={(e) => setFormData(prev => ({ ...prev, experimentName: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入试验名称"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                参试产品类型<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.productType}
                onChange={(e) => setFormData(prev => ({ ...prev, productType: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入参试产品类型"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验项目<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.testItems}
                onChange={(e) => setFormData(prev => ({ ...prev, testItems: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入试验项目"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验设备<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.testEquipment}
                onChange={(e) => setFormData(prev => ({ ...prev, testEquipment: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入试验设备"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验指挥<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <div style={{ position: 'relative' }}>
                <div 
                  data-dropdown="commander"
                  style={{ 
                    width: '100%', 
                    minHeight: '36px',
                    padding: '6px 8px', 
                    border: '1px solid #d9d9d9', 
                    borderRadius: '4px',
                    backgroundColor: 'white',
                    cursor: 'pointer',
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: '4px',
                    alignItems: 'center'
                  }}
                  onClick={() => {
                    const dropdown = document.getElementById('commander-dropdown')
                    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block'
                  }}
                >
                  {formData.experimentCommander ? 
                    formData.experimentCommander.split(',').map((name, index) => (
                      <span key={index} style={{
                        backgroundColor: '#e6f7ff',
                        border: '1px solid #91d5ff',
                        borderRadius: '4px',
                        padding: '2px 8px',
                        fontSize: '12px',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '4px'
                      }}>
                        {name.trim()}
                        <span 
                          style={{ cursor: 'pointer', fontWeight: 'bold' }}
                          onClick={(e) => {
                            e.stopPropagation()
                            const commanders = formData.experimentCommander.split(',').filter(n => n.trim() !== name.trim())
                            setFormData(prev => ({ ...prev, experimentCommander: commanders.join(',') }))
                          }}
                        >
                          ×
                        </span>
                      </span>
                    )) : 
                    <span style={{ color: '#999' }}>请选择试验指挥</span>
                  }
                </div>
                <div 
                  id="commander-dropdown"
                  style={{
                    position: 'absolute',
                    top: '100%',
                    left: 0,
                    right: 0,
                    backgroundColor: 'white',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    maxHeight: '200px',
                    overflowY: 'auto',
                    zIndex: 1000,
                    display: 'none'
                  }}
                >
                  {personnelList.map(person => {
                     const isSelected = formData.experimentCommander ? formData.experimentCommander.split(',').map(n => n.trim()).includes(person.name) : false
                     return (
                      <div
                        key={person.id}
                        style={{
                          padding: '8px 12px',
                          cursor: 'pointer',
                          backgroundColor: isSelected ? '#e6f7ff' : 'white',
                          ':hover': { backgroundColor: '#f5f5f5' }
                        }}
                        onMouseEnter={(e) => e.target.style.backgroundColor = isSelected ? '#e6f7ff' : '#f5f5f5'}
                        onMouseLeave={(e) => e.target.style.backgroundColor = isSelected ? '#e6f7ff' : 'white'}
                        onClick={() => {
                          const commanders = formData.experimentCommander ? formData.experimentCommander.split(',').map(n => n.trim()) : []
                          if (isSelected) {
                            const newCommanders = commanders.filter(n => n !== person.name)
                            setFormData(prev => ({ ...prev, experimentCommander: newCommanders.join(',') }))
                          } else {
                            commanders.push(person.name)
                            setFormData(prev => ({ ...prev, experimentCommander: commanders.join(',') }))
                          }
                        }}
                      >
                        <input 
                          type="checkbox" 
                          checked={isSelected}
                          readOnly
                          style={{ marginRight: '8px' }}
                        />
                        {person.name}
                      </div>
                    )
                  })}
                </div>
              </div>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                参试人员<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <div style={{ position: 'relative' }}>
                <div 
                  data-dropdown="participants"
                  style={{ 
                    width: '100%', 
                    minHeight: '36px',
                    padding: '6px 8px', 
                    border: '1px solid #d9d9d9', 
                    borderRadius: '4px',
                    backgroundColor: 'white',
                    cursor: 'pointer',
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: '4px',
                    alignItems: 'center'
                  }}
                  onClick={() => {
                    const dropdown = document.getElementById('participants-dropdown')
                    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block'
                  }}
                >
                  {formData.participants ? 
                    formData.participants.split(',').map((name, index) => (
                      <span key={index} style={{
                        backgroundColor: '#e6f7ff',
                        border: '1px solid #91d5ff',
                        borderRadius: '4px',
                        padding: '2px 8px',
                        fontSize: '12px',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '4px'
                      }}>
                        {name.trim()}
                        <span 
                          style={{ cursor: 'pointer', fontWeight: 'bold' }}
                          onClick={(e) => {
                            e.stopPropagation()
                            const participants = formData.participants.split(',').filter(n => n.trim() !== name.trim())
                            setFormData(prev => ({ ...prev, participants: participants.join(',') }))
                          }}
                        >
                          ×
                        </span>
                      </span>
                    )) : 
                    <span style={{ color: '#999' }}>请选择参试人员</span>
                  }
                </div>
                <div 
                  id="participants-dropdown"
                  style={{
                    position: 'absolute',
                    top: '100%',
                    left: 0,
                    right: 0,
                    backgroundColor: 'white',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px',
                    maxHeight: '200px',
                    overflowY: 'auto',
                    zIndex: 1000,
                    display: 'none'
                  }}
                >
                  {personnelList.map(person => {
                     const isSelected = formData.participants ? formData.participants.split(',').map(n => n.trim()).includes(person.name) : false
                     return (
                      <div
                        key={person.id}
                        style={{
                          padding: '8px 12px',
                          cursor: 'pointer',
                          backgroundColor: isSelected ? '#e6f7ff' : 'white',
                          ':hover': { backgroundColor: '#f5f5f5' }
                        }}
                        onMouseEnter={(e) => e.target.style.backgroundColor = isSelected ? '#e6f7ff' : '#f5f5f5'}
                        onMouseLeave={(e) => e.target.style.backgroundColor = isSelected ? '#e6f7ff' : 'white'}
                        onClick={() => {
                          const participants = formData.participants ? formData.participants.split(',').map(n => n.trim()) : []
                          if (isSelected) {
                            const newParticipants = participants.filter(n => n !== person.name)
                            setFormData(prev => ({ ...prev, participants: newParticipants.join(',') }))
                          } else {
                            participants.push(person.name)
                            setFormData(prev => ({ ...prev, participants: participants.join(',') }))
                          }
                        }}
                      >
                        <input 
                          type="checkbox" 
                          checked={isSelected}
                          readOnly
                          style={{ marginRight: '8px' }}
                        />
                        {person.name}
                      </div>
                    )
                  })}
                </div>
              </div>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                是否为协外试验<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <select
                value={formData.isExternalCollaboration}
                onChange={(e) => setFormData(prev => ({ ...prev, isExternalCollaboration: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              >
                <option value="否">否</option>
                <option value="是">是</option>
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                送试方部门/公司<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.testCompany}
                onChange={(e) => setFormData(prev => ({ ...prev, testCompany: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入适试方和厂/公司"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                送试方联系人及电话<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.testContact}
                onChange={(e) => setFormData(prev => ({ ...prev, testContact: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入适试方联系人及电话"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                参试产品名称<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.participantName}
                onChange={(e) => setFormData(prev => ({ ...prev, participantName: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入参试产品名称"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                参试产品数量<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.productQuantity}
                onChange={(e) => setFormData(prev => ({ ...prev, productQuantity: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入参试产品数量"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                参试产品编号<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.productNumber}
                onChange={(e) => setFormData(prev => ({ ...prev, productNumber: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入参试产品编号"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                产品入场日期<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.productEntryDate}
                onChange={(e) => setFormData(prev => ({ ...prev, productEntryDate: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验开始日期<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.testStartDate}
                onChange={(e) => setFormData(prev => ({ ...prev, testStartDate: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                试验结束日期<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.testEndDate}
                onChange={(e) => setFormData(prev => ({ ...prev, testEndDate: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                产品出场日期<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="date"
                value={formData.productExitDate}
                onChange={(e) => setFormData(prev => ({ ...prev, productExitDate: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              />
            </div>
            
            {selectedCategory === '真空热试验' && (
              <div>
                <label style={{ display: 'block', marginBottom: '4px' }}>
                  开机天数<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
                </label>
                <input
                  type="number"
                  value={formData.operatingDays}
                  onChange={(e) => setFormData(prev => ({ ...prev, operatingDays: e.target.value }))}
                  style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                  placeholder="请输入开机天数"
                  required
                />
              </div>
            )}
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>
                试验预约审批编号
              </label>
              <input
                type="text"
                value={formData.reservationApprovalNumber}
                onChange={(e) => setFormData(prev => ({ ...prev, reservationApprovalNumber: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入试验预约审批编号"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>
                试验照片是否上传<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <select
                value={formData.photoUploaded}
                onChange={(e) => setFormData(prev => ({ ...prev, photoUploaded: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                required
              >
                <option value="否">否</option>
                <option value="是">是</option>
              </select>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                总结报告/证明书<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <div style={{ display: 'flex', gap: '8px' }}>
                <select
                  value={formData.summaryReport === '信息化归档' || formData.summaryReport === '未编制' ? formData.summaryReport : ''}
                  onChange={(e) => setFormData(prev => ({ ...prev, summaryReport: e.target.value }))}
                  style={{ flex: 1, padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                >
                  <option value="">请选择或手填</option>
                  <option value="信息化归档">信息化归档</option>
                  <option value="未编制">未编制</option>
                </select>
                <input
                  type="text"
                  value={formData.summaryReport}
                  onChange={(e) => setFormData(prev => ({ ...prev, summaryReport: e.target.value }))}
                  style={{ flex: 1, padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                  placeholder="或手动输入"
                  required
                />
              </div>
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px' }}>
                证书归档编号<span style={{ color: 'red', marginLeft: '2px' }}>*</span>
              </label>
              <input
                type="text"
                value={formData.certificateNumber}
                onChange={(e) => setFormData(prev => ({ ...prev, certificateNumber: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入证书归档编号"
                required
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>合同编号</label>
              <input
                type="text"
                value={formData.contractNumber}
                onChange={(e) => setFormData(prev => ({ ...prev, contractNumber: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入合同编号"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>对方商务联系人及电话</label>
              <input
                type="text"
                value={formData.partnerContact}
                onChange={(e) => setFormData(prev => ({ ...prev, partnerContact: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入对方商务联系人及电话"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>我方商务联系人及电话</label>
              <input
                type="text"
                value={formData.ourContact}
                onChange={(e) => setFormData(prev => ({ ...prev, ourContact: e.target.value }))}
                style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: '4px' }}
                placeholder="请输入我方商务联系人及电话"
              />
            </div>
            
            <div>
              <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>原始记录上传</label>
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <label style={{ 
                  padding: '8px 16px', 
                  background: '#3498db', 
                  color: 'white', 
                  borderRadius: '4px',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '4px'
                }}>
                  <Upload size={16} />
                  上传附件
                  <input
                    type="file"
                    multiple
                    onChange={(e) => handleFileUpload(e, true)}
                    style={{ display: 'none' }}
                  />
                </label>
                <span style={{ fontSize: '12px', color: '#666' }}>
                  {formData.attachments.length > 0 ? `已上传 ${formData.attachments.length} 个文件` : '暂无附件'}
                </span>
              </div>
              {formData.attachments.length > 0 && (
                <div style={{ marginTop: '8px', maxHeight: '120px', overflowY: 'auto', border: '1px solid #eee', borderRadius: '4px', padding: '8px' }}>
                  {formData.attachments.map(attachment => (
                    <div key={attachment.id} style={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      padding: '4px 8px',
                      background: '#f8f9fa',
                      borderRadius: '4px',
                      marginBottom: '4px',
                      fontSize: '12px'
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', flex: 1, minWidth: 0 }}>
                        <FileText size={12} style={{ marginRight: '4px', flexShrink: 0 }} />
                        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={attachment.name}>
                          {attachment.name}
                        </span>
                      </div>
                      <button
                        type="button"
                        onClick={() => removeAttachment(attachment.id, true)}
                        style={{ background: 'none', border: 'none', color: '#e74c3c', cursor: 'pointer', marginLeft: '8px' }}
                        title="删除附件"
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            
            <div style={{ gridColumn: 'span 3', display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
              <button 
                type="button" 
                onClick={() => {
                  setShowAddForm(false)
                  setEditingExperiment(null)
                  setFormData({
                    experimentNumber: '',
                    experimentName: '',
                    productType: '',
                    testItems: '',
                    testEquipment: '',
                    experimentCommander: '',
                    participants: '',
                    isExternalCollaboration: '否',
                    testCompany: '',
                    testContact: '',
                    participantName: '',
                    productQuantity: '',
                    productNumber: '',
                    productEntryDate: '',
                    testStartDate: '',
                    testEndDate: '',
                    productExitDate: '',
                    operatingDays: '',
                    reservationApprovalNumber: '',
                    photoUploaded: '否',
                    summaryReport: '',
                    certificateNumber: '',
                    contractNumber: '',
                    partnerContact: '',
                    ourContact: '',
                    attachments: []
                  })
                }}
                style={{ 
                  padding: '8px 16px', 
                  border: '1px solid #d9d9d9', 
                  background: 'white', 
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button 
                type="submit"
                style={{ 
                  padding: '8px 16px', 
                  border: 'none', 
                  background: '#3498db', 
                  color: 'white',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                {editingExperiment ? '更新' : '保存'}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* 试验信息表格 */}
      <div className="table-container" style={{ 
        overflowX: 'auto', 
        overflowY: 'visible',
        border: '1px solid #e9ecef', 
        borderRadius: '8px',
        maxWidth: '100%',
        scrollbarWidth: 'thin',
        scrollbarColor: '#888 #f1f1f1',
        cursor: 'grab'
      }}>
        <table style={{ width: '100%', minWidth: '2000px', borderCollapse: 'collapse', fontSize: '12px' }}>
          <thead>
            <tr style={{ background: '#f8f9fa' }}>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '60px' }}>序号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验编号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验名称</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>参试产品类型</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>试验项目</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验设备</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验指挥</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>参试人员</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>是否为协外试验</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>送试方部门/公司</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>送试方联系人及电话</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>参试产品名称</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>参试产品数量</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>参试产品编号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>产品入场日期</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验开始日期</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>试验结束日期</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>产品出场日期</th>
              {selectedCategory === '真空热试验' && (
                <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '80px' }}>开机天数</th>
              )}
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '140px' }}>试验预约审批编号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>试验照片是否上传</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>总结报告/证明书</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '120px' }}>证书归档编号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '100px' }}>合同编号</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>对方商务联系人及电话</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>我方商务联系人及电话</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '150px' }}>原始记录上传</th>
              <th style={{ padding: '8px', border: '1px solid #dee2e6', minWidth: '80px' }}>操作</th>
            </tr>
          </thead>
        <tbody>
           {filteredExperiments.map((experiment, index) => (
             <tr key={experiment.id}>
               <td style={{ padding: '8px', border: '1px solid #dee2e6', fontWeight: '500', textAlign: 'center' }}>{index + 1}</td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'experimentNumber', experiment.experimentNumber)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'experimentName', experiment.experimentName)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'productType', experiment.productType)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderTestItemsCell(experiment)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'testEquipment', experiment.testEquipment)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'experimentCommander', experiment.experimentCommander, true, personnelList.map(person => ({value: person.name, label: person.name})))}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'participants', experiment.participants, true, personnelList.map(person => ({value: person.name, label: person.name})))}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'isExternalCollaboration', experiment.isExternalCollaboration, true, [{value: '是', label: '是'}, {value: '否', label: '否'}])}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'testCompany', experiment.testCompany)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'testContact', experiment.testContact)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'participantName', experiment.participantName)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'productQuantity', experiment.productQuantity)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'productNumber', experiment.productNumber)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'productEntryDate', experiment.productEntryDate)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'testStartDate', experiment.testStartDate)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'testEndDate', experiment.testEndDate)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'productExitDate', experiment.productExitDate)}
               </td>
               {selectedCategory === '真空热试验' && (
                 <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                   {renderEditableCell(experiment.id, 'operatingDays', 
                     calculateOperatingDays(experiment.testStartDate, experiment.testEndDate) || experiment.operatingDays
                   )}
                 </td>
               )}
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'reservationApprovalNumber', experiment.reservationApprovalNumber)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'photoUploaded', experiment.photoUploaded, true, [{value: '是', label: '是'}, {value: '否', label: '否'}])}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderSummaryReportCell(experiment)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'certificateNumber', experiment.certificateNumber)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'contractNumber', experiment.contractNumber)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'partnerContact', experiment.partnerContact)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderEditableCell(experiment.id, 'ourContact', experiment.ourContact)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 {renderAttachmentCell(experiment)}
               </td>
               <td style={{ padding: '8px', border: '1px solid #dee2e6' }}>
                 <div style={{ display: 'flex', gap: '4px', alignItems: 'center', justifyContent: 'center' }}>
                   <button 
                     onClick={() => startEditExperiment(experiment)}
                     style={{ 
                       border: 'none', 
                       background: 'none', 
                       cursor: 'pointer', 
                       color: '#3498db',
                       fontSize: '14px'
                     }}
                     title="修改"
                   >
                     <Edit2 size={14} />
                   </button>
                   <button 
                     onClick={() => deleteExperiment(experiment.id)}
                     style={{ 
                       border: 'none', 
                       background: 'none', 
                       cursor: 'pointer', 
                       color: '#e74c3c',
                       fontSize: '14px'
                     }}
                     title="删除"
                   >
                     <Trash2 size={14} />
                   </button>
                 </div>
               </td>
             </tr>
           ))}
        </tbody>
        </table>
      </div>

      {filteredExperiments.length === 0 && (
         <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
           暂无{selectedCategory}相关试验信息
         </div>
       )}
       
       {/* 统计信息 */}
       <div style={{ 
         marginTop: '16px', 
         padding: '12px', 
         background: '#f8f9fa', 
         borderRadius: '6px',
         fontSize: '14px',
         color: '#666'
       }}>
         <strong>统计信息：</strong>
         当前显示 {filteredExperiments.length} 条记录
         <span>（{selectedCategory}：{filteredExperiments.length} 条，占总数 {experiments.length > 0 ? Math.round((filteredExperiments.length / experiments.length) * 100) : 0}%）</span>
       </div>
       
       {/* 附件管理弹窗 */}
       {renderAttachmentModal()}
    </div>
  )
}

export default ExperimentStatistics